package com.sansan.qiangji.controller.base;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.sansan.qiangji.dto.ProductExcelDto;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.base.ProductAddForm;
import com.sansan.qiangji.form.base.ProductEditForm;
import com.sansan.qiangji.form.base.ProductListForm;
import com.sansan.qiangji.realize.base.ProductExcelListener;
import com.sansan.qiangji.realize.base.ProductReal;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@CrossOrigin()
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController  {

    @Autowired
    private ProductReal productReal;

    @PostMapping("/addProduct")
    public ResultVO<Object> addProduct(@Valid @RequestBody ProductAddForm productAddForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【物品新增】参数不正确，productAddForm={}",productAddForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        productReal.addProduct(productAddForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/getProductList")
    public ResultVO<Object> getProductList(@Valid @RequestBody ProductListForm form,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【物品查询】参数不正确，productAddForm={}",form);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        return ResultVOUtil.success(productReal.productList(form));
    }

    @PostMapping("/editProduct")
    public ResultVO<Object> editProduct(@Valid @RequestBody ProductEditForm productEditForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【物品修改】参数不正确，productAddForm={}",productEditForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        productReal.editProduct(productEditForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/editProductCondition")
    public ResultVO<Object> editProductCondition(@Valid @RequestBody ProductEditForm productEditForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【物品修改】参数不正确，productAddForm={}",productEditForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        productReal.editProductCondition(productEditForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/deleteProduct")
    public ResultVO<Object> deleteProduct(@RequestParam(value = "productId") Integer productId){
        productReal.deleteProduct(productId);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/getProductListCondition")
    public ResultVO<Object> getProductListCondition(@Valid @RequestBody ProductListForm form,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【物品查询】参数不正确，productAddForm={}",form);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        return ResultVOUtil.success(productReal.productListCondition(form));
    }

    @PostMapping("/upLoadProductExcel")
    public ResultVO<Object> upLoadProductExcel(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            EasyExcel.read(file.getInputStream(), ProductExcelDto.class, new ProductExcelListener(productReal)).excelType(ExcelTypeEnum.XLS).sheet().doRead();
        }catch (IOException e) {
            log.error("【上传物料表格】物料表格文件解析失败");
            throw e;
        }
        return ResultVOUtil.success(null);
    }

    @PostMapping("/upLoadProductPic")
    public ResultVO<Object> upLoadProductPic(@RequestParam("productCode") String productCode, @RequestParam("file") MultipartFile file){
        return ResultVOUtil.success(productReal.upLoadProductPic(productCode, file));
    }

    @PostMapping("/findByProductCode")
    public ResultVO<Object> findByProductCode(@RequestParam("productCode") String productCode){
        return ResultVOUtil.success(productReal.findByProductCode(productCode));
    }

    @GetMapping("/downloadProductTemplate")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("excelTemplate/product.xls");
        InputStream inputStream = classPathResource.getInputStream();
        Workbook workbook = new HSSFWorkbook(inputStream);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("product.xls", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @GetMapping("/downLoadProductExcel")
    public void downLoadProductExcel(HttpServletResponse response) throws Exception {
        List<ProductExcelDto> productExcelDtos = productReal.getAllProductDto();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("product.xls", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        EasyExcel.write(response.getOutputStream(), ProductExcelDto.class).excelType(ExcelTypeEnum.XLS).sheet("sheet1").doWrite(productExcelDtos);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
